<template>
  <el-dialog
    v-model="dialogVisible"
    title="最新评论"
    width="1200px"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="latest-comments">
      <!-- 筛选条件 -->
      <el-card class="filter-card">
        <el-form :model="queryForm" :inline="true" class="filter-form">
          <el-form-item label="文章ID">
            <el-input-number
              v-model="queryForm.articleId"
              :min="1"
              placeholder="文章ID"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item label="用户ID">
            <el-input-number
              v-model="queryForm.userId"
              :min="1"
              placeholder="用户ID"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item label="评论状态">
            <el-select
              v-model="queryForm.status"
              placeholder="选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="待审核" :value="0" />
              <el-option label="已通过" :value="1" />
              <el-option label="已拒绝" :value="2" />
              <el-option label="已删除" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input
              v-model="queryForm.keyword"
              placeholder="搜索关键词"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="queryForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <div class="advanced-options">
          <el-checkbox v-model="queryForm.onlyTopLevel">仅顶级评论</el-checkbox>
          <el-checkbox v-model="queryForm.includeSensitive"
            >包含敏感评论</el-checkbox
          >
          <span class="option-label">最小点赞数：</span>
          <el-input-number
            v-model="queryForm.minLikeCount"
            :min="0"
            size="small"
            style="width: 100px"
          />
          <span class="option-label">最小回复数：</span>
          <el-input-number
            v-model="queryForm.minReplyCount"
            :min="0"
            size="small"
            style="width: 100px"
          />
        </div>
      </el-card>

      <!-- 评论列表 -->
      <el-card class="comments-card">
        <template #header>
          <div class="card-header">
            <span>最新评论列表 ({{ pagination.total }}条)</span>
            <el-button size="small" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>

        <el-table :data="commentList" stripe>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="评论内容" min-width="200">
            <template #default="{ row }">
              <div class="comment-content">
                <p>{{ truncateContent(row.content) }}</p>
                <div class="comment-meta">
                  <el-tag size="small" type="info">{{
                    row.articleTitle
                  }}</el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="用户信息" width="150">
            <template #default="{ row }">
              <div class="user-info">
                <el-avatar
                  :size="32"
                  :src="formatAvatarUrl(row.userAvatar)"
                  fit="cover"
                >
                  <template #default>
                    <IconifyIconOnline icon="ep:user" />
                  </template>
                </el-avatar>
                <div class="user-details">
                  <div class="user-name">
                    {{ row.userNickName || row.userName }}
                  </div>
                  <div class="user-id">ID: {{ row.userId }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="互动数据" width="120">
            <template #default="{ row }">
              <div class="interaction-data">
                <div>👍 {{ row.likeCount }}</div>
                <div>💬 {{ row.replyCount }}</div>
                <div v-if="row.isSensitive" class="sensitive-mark">
                  <el-tag type="danger" size="small">敏感</el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { Search, Refresh } from "@element-plus/icons-vue";
import { IconifyIconOnline } from "@/components/ReIcon";
import {
  getLatestCommentsApi,
  type LatestCommentsQuery,
  type CommentInfo,
  CommentManagementUtils
} from "@/api/comment-management";

// Props
interface Props {
  visible: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
});

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  viewDetail: [comment: CommentInfo];
}>();

// 响应式数据
const loading = ref(false);
const commentList = ref<CommentInfo[]>([]);

const queryForm = reactive({
  articleId: undefined,
  userId: undefined,
  status: undefined,
  keyword: "",
  dateRange: null,
  onlyTopLevel: false,
  includeSensitive: true,
  minLikeCount: undefined,
  minReplyCount: undefined
});

const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
});

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

// 方法
const loadCommentList = async () => {
  try {
    loading.value = true;

    const params: LatestCommentsQuery = {
      current: pagination.current,
      size: pagination.size,
      ...queryForm
    };

    // 处理时间范围
    if (queryForm.dateRange) {
      params.startTime = queryForm.dateRange[0];
      params.endTime = queryForm.dateRange[1];
    }

    // 清理空值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === "") {
        delete params[key];
      }
    });

    const response = await getLatestCommentsApi(params);

    if (response.code === 200) {
      commentList.value = response.data.records;
      pagination.total = response.data.total;
    } else {
      ElMessage.error(response.message || "获取最新评论失败");
    }
  } catch (error) {
    console.error("获取最新评论失败:", error);
    ElMessage.error("获取最新评论失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  loadCommentList();
};

const handleReset = () => {
  Object.assign(queryForm, {
    articleId: undefined,
    userId: undefined,
    status: undefined,
    keyword: "",
    dateRange: null,
    onlyTopLevel: false,
    includeSensitive: true,
    minLikeCount: undefined,
    minReplyCount: undefined
  });
  pagination.current = 1;
  loadCommentList();
};

const handleRefresh = () => {
  loadCommentList();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadCommentList();
};

const handleCurrentChange = (current: number) => {
  pagination.current = current;
  loadCommentList();
};

const handleViewDetail = (comment: CommentInfo) => {
  emit("viewDetail", comment);
};

const handleClose = () => {
  dialogVisible.value = false;
};

// 工具方法
const truncateContent = (content: string) => {
  return CommentManagementUtils.truncateContent(content, 50);
};

const formatDateTime = (time: string) => {
  return CommentManagementUtils.formatTime(time);
};

const formatAvatarUrl = (url: string): string => {
  if (!url) return "";
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};

const getStatusText = (status: number) => {
  return CommentManagementUtils.getStatusText(status);
};

const getStatusTagType = (status: number) => {
  return CommentManagementUtils.getStatusTagType(status);
};

// 监听对话框显示
watch(
  () => props.visible,
  visible => {
    if (visible) {
      loadCommentList();
    }
  }
);
</script>

<style scoped lang="scss">
.latest-comments {
  .filter-card {
    margin-bottom: 16px;

    .filter-form {
      .el-form-item {
        margin-bottom: 16px;
      }
    }

    .advanced-options {
      display: flex;
      gap: 16px;
      align-items: center;
      padding-top: 16px;
      margin-top: 16px;
      border-top: 1px solid #e4e7ed;

      .option-label {
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .comments-card {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .comment-content {
      .comment-meta {
        margin-top: 8px;
      }
    }

    .user-info {
      display: flex;
      gap: 8px;
      align-items: center;

      .user-details {
        .user-name {
          font-size: 14px;
          font-weight: 500;
        }

        .user-id {
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .interaction-data {
      font-size: 12px;
      color: #606266;

      div {
        margin-bottom: 4px;
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 16px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
